/*-------------------------------------------------------------------------
 * CLR版本:     4.0.30319.42000
 * 创建人:      song
 * 创建时间：   2024/4/9 14:47:37
 * 功 能：     设置值
 *-------------------------------------------------------------------------*/

using System;
using UnityEngine;

namespace SCore.UI
{
    [Serializable]
    public class SOptionalFloat : SOptional<float>
    {
        public static SOptionalFloat WithValue(float value)
        {
            return new SOptionalFloat { IsSet = true, Value = value };
        }
    }

    [Serializable]
    public class SOptionalInt : SOptional<int>
    {
        public static SOptionalInt WithValue(int value)
        {
            return new SOptionalInt { IsSet = true, Value = value };
        }
    }

    [Serializable]
    public class SOptionalString : SOptional<string>
    {
        public static SOptionalString WithValue(string value)
        {
            return new SOptionalString { IsSet = true, Value = value };
        }
    }

    [Serializable]
    public class SOptionalKeyCode : SOptional<KeyCode>
    {
        public static SOptionalKeyCode WithValue(KeyCode value)
        {
            return new SOptionalKeyCode { IsSet = true, Value = value };
        }
    }

    [Serializable]
    public class SOptionalGameObject : SOptional<GameObject>
    {
    }

    [Serializable]
    public class SOptionalComponent : SOptional<Component>
    {
    }

    [Serializable]
    public class SOptional<T> : SOptionalParent
    {
        public bool IsSet;
        public T Value;
    }

    [Serializable]
    public class SOptionalParent
    {
    }
}

#if UNITY_EDITOR
namespace SCore.UI
{
    using UnityEditor;

    [CustomPropertyDrawer(typeof(SOptionalParent), true)]
    public class OptionalTypePropertyDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);
            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
            var indentLevelBackup = EditorGUI.indentLevel; // Backup indent before fix
            EditorGUI.indentLevel = 0; // PropertyDrawer Indent fix for nested inspectors

            var value = property.FindPropertyRelative("Value");
            var isSet = property.FindPropertyRelative("IsSet");

            var checkWidth = 14;
            var spaceWidth = 4;
            var valWidth = position.width - checkWidth - spaceWidth;

            position.width = checkWidth;
            isSet.boolValue = EditorGUI.Toggle(position, GUIContent.none, isSet.boolValue);

            position.x += checkWidth + spaceWidth;
            position.width = valWidth;
            if (isSet.boolValue) EditorGUI.PropertyField(position, value, GUIContent.none);
            EditorGUI.EndProperty();
            EditorGUI.indentLevel = indentLevelBackup; // restore indent backup
        }
    }
}
#endif